<?php

class OrderAction extends AdminAction
{
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * 订单列表
     */
    public function index()
    {
        //登录用户信息
        $user = Session('admin');
        $user_id = $user['user_id'];

        //获取已经投放的广告
        $ad_putRelationship = M("putrelationship");
        $adInfo = $ad_putRelationship->where(array('advertising_user_id'=>$user_id))
            ->order('rel_id desc')
            ->field('advertising_id, advertising_name')
            ->select();

        //获取所有网站
        $site = M('site');
        $siteInfo = $site->field('site_id, site_name')->select();

        $isSelect = intval(I('isSelect'));

        if ($isSelect) {
            //广告ID
            $advertising_id = intval(I('advertising_id'));

            //网站ID
            $site_id = intval(I('site_id'));

            //分页每页的条数
            $perPage = $this->getPerPage();

            //查询条件
            $where = array();
            $where['advertising_id'] = $advertising_id;
            $where['site_id'] = $site_id;

            $currPage = intval($_GET['p']);
            $currPage < 1 && $currPage = 1;

            $ad_order = M("order");

            $itemCount = $ad_order->where($where)->count();
            $data = $ad_order->where($where)->order('order_id desc')->limit(($currPage-1)*$perPage, $perPage)->select();

            $itemPerPage = $perPage;
            $pageUrl = $this->baseUrl . '/Admin/Order/index';
            $paramQuery = array('advertising_id'=>$advertising_id, 'site_id'=>$site_id, 'isSelect'=>$isSelect);
            $paginator = new Paginator($currPage, $itemCount, $itemPerPage, $pageUrl, $paramQuery);

            $page = $paginator->getHtml(1);

        }

        $this->assign('baseUrl', $this->baseUrl);
        $this->assign('adInfo', $adInfo);
        $this->assign('siteInfo', $siteInfo);
        $this->assign('data', $data);
        $this->assign('page', $page);
        $this->assign('advertising_id', $advertising_id);
        $this->assign('site_id', $site_id);

        $this->display();
    }

    /**
     * 网站对接
     */
    public function siteCallback()
    {
        /*
         * http://localhost/advertising/index.php/Admin/Order/siteCallback?source=28E6UG8KWHI=&tid=qwe&uid=123&username=lzw
         */
        //来源字符串
        $source = I('source');
        //媒介生成的用户唯一标识符
        $site_tid = I('tid');
        //网站用户ID，可为空
        $site_uid = I('uid', 0);
        //网站用户名，可为空
        $site_username = I('username', '');

        if (empty($site_tid)) {
            $result = array('status'=>3, 'message'=>"参数tid为空");
            echo json_encode($result);
            exit;
        }

        //解密来源字符串
        $source = decrypt_str($source);
        list($advertising_id, $site_id) = explode("\t",$source);

        $ad_putRelationship = M("putrelationship");

        //广告和网站相关信息
        $putRelationship = $ad_putRelationship->where(array('advertising_id'=>$advertising_id, 'site_id'=>$site_id))
            ->field('rel_id, advertising_id, advertising_name, advertising_user_id, site_id, site_name, site_user_id')
            ->find();

        if (empty($putRelationship)) {
            $result = array('status'=>2, 'message'=>"没有该广告或者网站");
            echo json_encode($result);
            exit;
        }

        $ad_order = M('order');

        //判断是否在推送同一用户
        $orderCount = $ad_order->where(array('advertising_id'=>$advertising_id, 'site_id'=>$site_id, 'site_tid'=>$site_tid))->count();
        if ($orderCount) {
            $result = array('status'=>4, 'message'=>"重复推送同一用户");
            echo json_encode($result);
            exit;
        }

        $data = array(
            'putrelationship_id'  => $putRelationship['rel_id'],
            'advertising_id'      => $putRelationship['advertising_id'],
            'advertising_name'    => $putRelationship['advertising_name'],
            'advertising_user_id' => $putRelationship['advertising_user_id'],
            'site_id'             => $putRelationship['site_id'],
            'site_name'           => $putRelationship['site_name'],
            'site_user_id'        => $putRelationship['site_user_id'],
            'site_tid'            => $site_tid,
            'site_uid'            => $site_uid,
            'site_username'       => $site_username,
            'create_time'         => time()
        );


        $re = $ad_order->add($data);
        if ($re) {
            $result = array('status'=>0, 'message'=>"推送成功");
        } else {
            $result = array('status'=>1, 'message'=>"网络原因推送失败，请稍后重试");
        }

        /*
         * status
         * 0 推送成功
         * 1 网络原因推送失败，请稍后重试
         * 2 没有该广告或者网站
         * 3 参数tid为空
         * 4 重复推送同一用户
         */
        echo json_encode($result);

    }

    /**
     * 广告对接
     */
    public function adCallback()
    {
        /*
         * http://localhost/advertising/index.php/Admin/Order/adCallback?tid=qwe&step=1,2,3&uid=123&username=lzw
         */

        //用户唯一标识符
        $tid = I('tid');
        //完成的步骤
        $step = I('step');
        //广告用户ID，可为空
        $uid = I('uid', 0);
        //广告用户名，可为空
        $username = I('username', '');

        if (empty($tid) || empty($step)) {
            $result = array('status'=>2, 'message'=>"参数tid或者step为空");
            echo json_encode($result);
            exit;
        }

        $ad_order = M('order');

        $where = array('site_tid'=>$tid);

        //判断是否在推送不存在用户
        $order_info = $ad_order->where($where)->find();
        if (empty($order_info)) {
            $result = array('status'=>3, 'message'=>"没有该用户");
            echo json_encode($result);
            exit;
        }

        $data = array(
            'ad_uid'      => $uid,
            'ad_username' => $username,
            'finish_step' => "," . $step . ",",
            'back_time'   => time(),
            'update_time' => time()
        );


        $re = $ad_order->where(array('site_tid'=>$tid))->save($data);
        if ($re) {
            $result = array('status'=>0, 'message'=>"推送成功");

            //想网站推送数据
            $this->sendDataToSite($tid, $order_info['site_id'], $step);

        } else {
            $result = array('status'=>1, 'message'=>"网络原因推送失败，请稍后重试");
        }

        /*
         * status
         * 0 推送成功
         * 1 网络原因推送失败，请稍后重试
         * 2 参数tid或者step为空
         * 3 没有该用户
         */
        echo json_encode($result);
    }

    private function sendDataToSite($tid, $site_id, $step)
    {
        $site = M('site');
        $site_info = $site->where(array('site_id'=>$site_id))->field('send_data')->find();

        $ad_order = M('order');

        $data = array('tid'=>$tid, 'step'=>$step);

        if (strpos($site_info['send_data'], '?') !== false) {
            $url = $site_info['send_data'] . '&' . http_build_query($data);
        } else {
            $url = $site_info['send_data'] . '?' . http_build_query($data);
        }

        // 初始化一个 cURL 对象
        $curl = curl_init();

        // 设置你需要抓取的URL
        curl_setopt($curl, CURLOPT_URL, $url);

        // 设置header
        curl_setopt($curl, CURLOPT_HEADER, 0);

        // 设置cURL 参数，要求结果保存到字符串中还是输出到屏幕上。
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);

        // 运行cURL，请求网页
        $data = curl_exec($curl);

        // 关闭URL请求
        curl_close($curl);

        // 显示获得的数据
        var_dump($data);

    }

}


?>